<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Spring 源码学习 15：finishBeanFactoryInitialization（重点） | 程序员小航</title><meta name="keywords" content="Spring,源码笔记"><meta name="author" content="liuzhihang"><meta name="copyright" content="liuzhihang"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="可以说前面的都是准备工作，而接下来开始的才是重点，在这一步会完成 BeanFactory 的初始化，同时实例化单例 Bean。">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring 源码学习 15：finishBeanFactoryInitialization（重点）">
<meta property="og:url" content="https://liuzhihang.com/2021/01/12/source-spring-15.html">
<meta property="og:site_name" content="程序员小航">
<meta property="og:description" content="可以说前面的都是准备工作，而接下来开始的才是重点，在这一步会完成 BeanFactory 的初始化，同时实例化单例 Bean。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/II1QBD-L3tiN3.png">
<meta property="article:published_time" content="2021-01-12T13:40:00.000Z">
<meta property="article:modified_time" content="2021-01-18T08:23:49.239Z">
<meta property="article:author" content="liuzhihang">
<meta property="article:tag" content="Spring">
<meta property="article:tag" content="源码笔记">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/II1QBD-L3tiN3.png"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/favicon.ico"><link rel="canonical" href="https://liuzhihang.com/2021/01/12/source-spring-15"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//pingjs.qq.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google_site_verification" content="GZshAnnrC-4eCrl5h-e_5Rdk4lOUhRK7ShULoRi2q0E"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-126394362-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-126394362-1');
</script><script>var _mtac = {};
(function() {
    var mta = document.createElement("script");
    mta.src = "//pingjs.qq.com/h5/stats.js?v2.0.4";
    mta.setAttribute("name", "MTAH5");
    mta.setAttribute("sid", "66540676");
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(mta, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":730,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring 源码学习 15：finishBeanFactoryInitialization（重点）',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-01-18 16:23:49'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="//at.alicdn.com/t/font_1608878_xsf93f0c1a.css"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="程序员小航" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/II1QBD-L3tiN3.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">程序员小航</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring 源码学习 15：finishBeanFactoryInitialization（重点）</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-01-12T13:40:00.000Z" title="发表于 2021-01-12 21:40:00">2021-01-12</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-01-18T08:23:49.239Z" title="更新于 2021-01-18 16:23:49">2021-01-18</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/Spring/">Spring</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>13分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Spring 源码学习 15：finishBeanFactoryInitialization（重点）"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2021/01/12/source-spring-15.html#post-comment"><span class="gitalk-comment-count"></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>可以说前面的都是准备工作，而接下来开始的才是重点，在这一步会完成 BeanFactory 的初始化，同时实例化单例 Bean。</p>
<p>具体怎么操作的，那就一起阅读源码吧！</p>
<p>不过在阅读源码之前，还是需要了解一些知识的。</p>
<ol>
<li>什么是 FactoryBean ？</li>
<li>FactoryBean 是如何使用的 ？ </li>
<li>Bean 是如何初始化的？</li>
<li>常说的循环依赖是怎么解决的？</li>
</ol>
<h3 id="什么是-FactoryBean-？"><a href="#什么是-FactoryBean-？" class="headerlink" title="什么是 FactoryBean ？"></a>什么是 FactoryBean ？</h3><p>在官网的这篇文章<a target="_blank" rel="noopener" href="https://spring.io/blog/2011/08/09/what-s-a-factorybean" title="What&#39;s a FactoryBean?">《What’s a FactoryBean?》</a>中有相关解答，有兴趣的小伙伴可以看一下。</p>
<p>由内部使用的对象实现的接口，这些对象 BeanFactory 本身就是单个对象的工厂。如果 bean 实现此接口，则它将用作对象公开的工厂，而不是直接用作将自身公开的 bean 实例。</p>
<p>注意：实现此接口的 bean 不能用作普通 bean。 FactoryBean以 bean 样式定义，但是为 bean 引用（getObject()）公开的对象始终是它创建的对象。</p>
<p>FactoryBeans 可以支持单例和原型，并且可以按需延迟创建对象，也可以在启动时急于创建对象。</p>
<p>当生命一个 FactoryBean 时，会存在两个类型的 Bean，分别是 FactoryBean 本身，以及它需要创建的类型的 Bean。</p>
<p>下面是使用示例：</p>
<h3 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h3><h4 id="1-PaidComponent"><a href="#1-PaidComponent" class="headerlink" title="1. PaidComponent"></a>1. PaidComponent</h4><pre><code class="java">public class PaidComponent &#123;

    public PaidComponent() &#123;
        System.out.println(&quot;PaidComponent 无参构造被调用&quot;);
    &#125;
&#125;</code></pre>
<h4 id="2-PaidComponentFactoryBean"><a href="#2-PaidComponentFactoryBean" class="headerlink" title="2. PaidComponentFactoryBean"></a>2. PaidComponentFactoryBean</h4><pre><code class="java">@Component
public class PaidComponentFactoryBean implements FactoryBean&lt;PaidComponent&gt; &#123;

    @Override
    public PaidComponent getObject() throws Exception &#123;

        System.out.println(&quot;PaidComponentFactoryBean 的 getObject 方法被调用&quot;);

        return new PaidComponent();
    &#125;

    @Override
    public Class&lt;?&gt; getObjectType() &#123;
        return PaidComponent.class;
    &#125;

&#125;</code></pre>
<h4 id="3-Test"><a href="#3-Test" class="headerlink" title="3 Test"></a>3 Test</h4><pre><code class="java">public class AnnotationConfigApplicationTest &#123;

    public static void main(String[] args) &#123;

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        context.register(JavaConfig.class);


        context.refresh();


        System.out.println(context.getBean(&quot;paidComponentFactoryBean&quot;));
        System.out.println(context.getBean(&quot;&amp;paidComponentFactoryBean&quot;));
        System.out.println(context.getBean(PaidComponent.class));

    &#125;
&#125;
</code></pre>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/5Ho48G-UVQwo4.png"></p>
<p>可以看出注册了两个 Bean， 一个是 <code>paidComponentFactoryBean</code> ，另一个是 <code>&amp;paidComponentFactoryBean</code>。</p>
<p>而直接获取 <code>paidComponentFactoryBean</code> 获取到的其实是 FactoryBean 的 <code>getObject()</code> 方法返回的类型。</p>
<h3 id="finishBeanFactoryInitialization-源码"><a href="#finishBeanFactoryInitialization-源码" class="headerlink" title="finishBeanFactoryInitialization 源码"></a>finishBeanFactoryInitialization 源码</h3><pre><code class="java">protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) &#123;
    // Initialize conversion service for this context.
    // 初始化类型转换器
    if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &amp;&amp;
            beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) &#123;
        beanFactory.setConversionService(
                beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
    &#125;

    // Register a default embedded value resolver if no bean post-processor
    // (such as a PropertyPlaceholderConfigurer bean) registered any before:
    // at this point, primarily for resolution in annotation attribute values.
    // 主要用于注释属性值的解析
    if (!beanFactory.hasEmbeddedValueResolver()) &#123;
        beanFactory.addEmbeddedValueResolver(strVal -&gt; getEnvironment().resolvePlaceholders(strVal));
    &#125;

    // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
    // 尽早初始化 LoadTimeWeaverAware Bean，以便尽早注册其转换器。
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) &#123;
        getBean(weaverAwareName);
    &#125;

    // Stop using the temporary ClassLoader for type matching.
    // 停止使用临时的ClassLoader进行类型匹配。
    beanFactory.setTempClassLoader(null);

    // Allow for caching all bean definition metadata, not expecting further changes.
    // 设置 beanDefinition 元数据 不可以再修改
    beanFactory.freezeConfiguration();

    // Instantiate all remaining (non-lazy-init) singletons.
    // 实例化单例 bean
    beanFactory.preInstantiateSingletons();
&#125;</code></pre>
<p>这里重点关注最后一行</p>
<p><code>beanFactory.preInstantiateSingletons();</code></p>
<h4 id="preInstantiateSingletons"><a href="#preInstantiateSingletons" class="headerlink" title="preInstantiateSingletons"></a>preInstantiateSingletons</h4><p>这块进入的是类  <code>DefaultListableBeanFactory</code> 类的源码。</p>
<pre><code class="java">public void preInstantiateSingletons() throws BeansException &#123;
    if (logger.isTraceEnabled()) &#123;
        logger.trace(&quot;Pre-instantiating singletons in &quot; + this);
    &#125;

    // Iterate over a copy to allow for init methods which in turn register new bean definitions.
    // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
    // 将 beanDefinitionNames 放到集合中
    List&lt;String&gt; beanNames = new ArrayList&lt;&gt;(this.beanDefinitionNames);

    // Trigger initialization of all non-lazy singleton beans...
    // 遍历
    for (String beanName : beanNames) &#123;
        // 获取 bd 信息, 因为可能 定义了 parentBeanDefinition
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        // 非抽象, 单例, 且不是懒加载
        if (!bd.isAbstract() &amp;&amp; bd.isSingleton() &amp;&amp; !bd.isLazyInit()) &#123;
            // 判断是否为 FactoryBean
            if (isFactoryBean(beanName)) &#123;
                // FactoryBean 需要添加前缀 &amp; ,通过 getBean(&amp;beanName) 获取的是 FactoryBean 本身
                Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                if (bean instanceof FactoryBean) &#123;
                    FactoryBean&lt;?&gt; factory = (FactoryBean&lt;?&gt;) bean;
                    // 判断是否需要初始化
                    boolean isEagerInit;
                    if (System.getSecurityManager() != null &amp;&amp; factory instanceof SmartFactoryBean) &#123;
                        isEagerInit = AccessController.doPrivileged(
                                (PrivilegedAction&lt;Boolean&gt;) ((SmartFactoryBean&lt;?&gt;) factory)::isEagerInit,
                                getAccessControlContext());
                    &#125;
                    else &#123;
                        isEagerInit = (factory instanceof SmartFactoryBean &amp;&amp;
                                ((SmartFactoryBean&lt;?&gt;) factory).isEagerInit());
                    &#125;
                    // 需要初始化
                    if (isEagerInit) &#123;
                        getBean(beanName);
                    &#125;
                &#125;
            &#125;
            else &#123;
                getBean(beanName);
            &#125;
        &#125;
    &#125;

    // Trigger post-initialization callback for all applicable beans...
    // 如果 Bean 实现了 SmartInitializingSingleton,
    // 在这里会统一调用 afterSingletonsInstantiated 方法
    for (String beanName : beanNames) &#123;
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) &#123;
            StartupStep smartInitialize = this.getApplicationStartup().start(&quot;spring.beans.smart-initialize&quot;)
                    .tag(&quot;beanName&quot;, beanName);
            SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) &#123;
                AccessController.doPrivileged((PrivilegedAction&lt;Object&gt;) () -&gt; &#123;
                    smartSingleton.afterSingletonsInstantiated();
                    return null;
                &#125;, getAccessControlContext());
            &#125;
            else &#123;
                smartSingleton.afterSingletonsInstantiated();
            &#125;
            smartInitialize.end();
        &#125;
    &#125;
&#125;</code></pre>
<p>上面方法中通过循环 <code>beanNames</code> 进行初始化 Bean。</p>
<p>其中需要区别 BeanFactory 和 普通 Bean。 这也是我开始为什么先介绍了<code>什么是 BeanFactory ?</code></p>
<p>下面就需要重点关注 <code>getBean(beanName)</code> 方法。</p>
<h4 id="getBean"><a href="#getBean" class="headerlink" title="getBean"></a>getBean</h4><pre><code class="java">public Object getBean(String name) throws BeansException &#123;
    return doGetBean(name, null, null, false);
&#125;</code></pre>
<p>在 <code>getBean</code> 方法中调用的是 <code>doGetBean</code> 方法。</p>
<h4 id="doGetBean"><a href="#doGetBean" class="headerlink" title="doGetBean"></a>doGetBean</h4><p>doGetBean 方法作用是：<code>返回一个实例，该实例可以是指定bean的共享或独立的</code>。 </p>
<p>该方法接受四个参数：</p>
<blockquote>
<p>name – 要检索的 bean 的名称<br>requiredType – 要检索的 bean 的必需类型，这个可以为空<br>args –使用显式参数创建bean实例时要使用的参数（仅在创建新实例而不是检索现有实例时才应用）<br>typeCheckOnly –是否为类型检查而不是实际使用获取实例</p>
</blockquote>
<pre><code class="java">protected &lt;T&gt; T doGetBean(
        String name, @Nullable Class&lt;T&gt; requiredType, @Nullable Object[] args, boolean typeCheckOnly)
        throws BeansException &#123;

    // 去掉工厂引用的前缀, 同时转换别名
    String beanName = transformedBeanName(name);
    Object bean;

    // Eagerly check singleton cache for manually registered singletons.
    // 从缓存中检查单例是否已经存在
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null &amp;&amp; args == null) &#123;
        if (logger.isTraceEnabled()) &#123;
            if (isSingletonCurrentlyInCreation(beanName)) &#123;
                logger.trace(&quot;Returning eagerly cached instance of singleton bean &#39;&quot; + beanName +
                        &quot;&#39; that is not fully initialized yet - a consequence of a circular reference&quot;);
            &#125;
            else &#123;
                logger.trace(&quot;Returning cached instance of singleton bean &#39;&quot; + beanName + &quot;&#39;&quot;);
            &#125;
        &#125;
        // 从缓存中如果获取到了, 普通 Bean 直接返回, FactoryBean 则返回 FactoryBean 创建的 Bean
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    &#125;

    else &#123;
        // Fail if we&#39;re already creating this bean instance:
        // We&#39;re assumably within a circular reference.
        // 返回指定的 原型bean (prototype 类型的 Bean) 是否当前正在创建中（在当前线程内）。
        if (isPrototypeCurrentlyInCreation(beanName)) &#123;
            throw new BeanCurrentlyInCreationException(beanName);
        &#125;

        // Check if bean definition exists in this factory.
        // 检查 BeanFactory 是否存在这个 Bean 的 BeanDefinition
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null &amp;&amp; !containsBeanDefinition(beanName)) &#123;
            // Not found -&gt; check parent.
            // 检查父容器中有没有定义
            String nameToLookup = originalBeanName(name);
            // 返回从父容器中查询的结果
            if (parentBeanFactory instanceof AbstractBeanFactory) &#123;
                return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                        nameToLookup, requiredType, args, typeCheckOnly);
            &#125;
            else if (args != null) &#123;
                // Delegation to parent with explicit args.
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            &#125;
            else if (requiredType != null) &#123;
                // No args -&gt; delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            &#125;
            else &#123;
                return (T) parentBeanFactory.getBean(nameToLookup);
            &#125;
        &#125;

        if (!typeCheckOnly) &#123;
            // 将当前 beanName 放入一个 alreadyCreated 的 Set 集合中。
            // 标识本次调用方法，并非是要获取bean的类型，而是为了创建实例，将beanName存到alreadyCreated集合，代表该bean已经创建了，后面try。。catch有异常会清空该beanName
            markBeanAsCreated(beanName);
        &#125;

        StartupStep beanCreation = this.applicationStartup.start(&quot;spring.beans.instantiate&quot;)
                .tag(&quot;beanName&quot;, name);
        try &#123;
            if (requiredType != null) &#123;
                beanCreation.tag(&quot;beanType&quot;, requiredType::toString);
            &#125;
            // 获取 Bean 的 BeanDefinition
            RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);

            // Guarantee initialization of beans that the current bean depends on.
            // 确保依赖的 Bean 已经被初始化, 比如 @DependsOn 注解
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) &#123;
                for (String dep : dependsOn) &#123;
                    if (isDependent(beanName, dep)) &#123;
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                &quot;Circular depends-on relationship between &#39;&quot; + beanName + &quot;&#39; and &#39;&quot; + dep + &quot;&#39;&quot;);
                    &#125;
                    registerDependentBean(dep, beanName);
                    try &#123;
                        // 创建依赖的 Bean
                        getBean(dep);
                    &#125;
                    catch (NoSuchBeanDefinitionException ex) &#123;
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                &quot;&#39;&quot; + beanName + &quot;&#39; depends on missing bean &#39;&quot; + dep + &quot;&#39;&quot;, ex);
                    &#125;
                &#125;
            &#125;

            // Create bean instance.
            if (mbd.isSingleton()) &#123;
                // 单例 bean
                sharedInstance = getSingleton(beanName, () -&gt; &#123;
                    try &#123;
                        return createBean(beanName, mbd, args);
                    &#125;
                    catch (BeansException ex) &#123;
                        // Explicitly remove instance from singleton cache: It might have been put there
                        // eagerly by the creation process, to allow for circular reference resolution.
                        // Also remove any beans that received a temporary reference to the bean.
                        destroySingleton(beanName);
                        throw ex;
                    &#125;
                &#125;);
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            &#125;
            // 创建原型Bean
            else if (mbd.isPrototype()) &#123;
                // It&#39;s a prototype -&gt; create a new instance.
                Object prototypeInstance = null;
                try &#123;
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                &#125;
                finally &#123;
                    afterPrototypeCreation(beanName);
                &#125;
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            &#125;

            else &#123;
                // 委托给实现类处理
                String scopeName = mbd.getScope();
                if (!StringUtils.hasLength(scopeName)) &#123;
                    throw new IllegalStateException(&quot;No scope name defined for bean ´&quot; + beanName + &quot;&#39;&quot;);
                &#125;
                Scope scope = this.scopes.get(scopeName);
                if (scope == null) &#123;
                    throw new IllegalStateException(&quot;No Scope registered for scope name &#39;&quot; + scopeName + &quot;&#39;&quot;);
                &#125;
                try &#123;
                    Object scopedInstance = scope.get(beanName, () -&gt; &#123;
                        beforePrototypeCreation(beanName);
                        try &#123;
                            return createBean(beanName, mbd, args);
                        &#125;
                        finally &#123;
                            afterPrototypeCreation(beanName);
                        &#125;
                    &#125;);
                    bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                &#125;
                catch (IllegalStateException ex) &#123;
                    throw new ScopeNotActiveException(beanName, scopeName, ex);
                &#125;
            &#125;
        &#125;
        catch (BeansException ex) &#123;
            beanCreation.tag(&quot;exception&quot;, ex.getClass().toString());
            beanCreation.tag(&quot;message&quot;, String.valueOf(ex.getMessage()));
            cleanupAfterBeanCreationFailure(beanName);
            throw ex;
        &#125;
        finally &#123;
            beanCreation.end();
        &#125;
    &#125;

    // Check if required type matches the type of the actual bean instance.
    // 检查所需的类型是否与实际bean实例的类型匹配。
    if (requiredType != null &amp;&amp; !requiredType.isInstance(bean)) &#123;
        try &#123;
            T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
            if (convertedBean == null) &#123;
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            &#125;
            return convertedBean;
        &#125;
        catch (TypeMismatchException ex) &#123;
            if (logger.isTraceEnabled()) &#123;
                logger.trace(&quot;Failed to convert bean &#39;&quot; + name + &quot;&#39; to required type &#39;&quot; +
                        ClassUtils.getQualifiedName(requiredType) + &quot;&#39;&quot;, ex);
            &#125;
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        &#125;
    &#125;
    return (T) bean;
&#125;</code></pre>
<p>上面代码比较长，基本上步骤已经添加相应的注释，基本上可以分为三步：</p>
<ol>
<li>从缓存中获取到 Bean，创建对应的 Bean；</li>
<li>没有从缓存中获取到 Bean，创建对应的 Bean；</li>
<li>检查所需的类型是否与实际bean实例的类型匹配。</li>
</ol>
<p>下面从这三个步骤分别介绍：</p>
<ul>
<li>从缓存中获取到 Bean，创建对应的 Bean</li>
</ul>
<p><strong><code>Object sharedInstance = getSingleton(beanName);</code></strong></p>
<pre><code class="java">public Object getSingleton(String beanName) &#123;
    return getSingleton(beanName, true);
&#125;
/**
 * 返回以给定名称注册的（原始）单例对象。
 *
 * 检查已经实例化的单例，并允许早期引用当前创建的单例（解析循环引用）
 */
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) &#123;
    // Quick check for existing instance without full singleton lock
    // private final Map&lt;String, Object&gt; singletonObjects = new ConcurrentHashMap&lt;&gt;(256);
    // 缓存了 单例 Bean
    Object singletonObject = this.singletonObjects.get(beanName);
    // 如果没有获取到, 并且当前 Bean 正在被创建中
    if (singletonObject == null &amp;&amp; isSingletonCurrentlyInCreation(beanName)) &#123;
        // private final Map&lt;String, Object&gt; earlySingletonObjects = new ConcurrentHashMap&lt;&gt;(16);
        // 早期的单例对象, 先从 earlySingletonObjects 中获取
        singletonObject = this.earlySingletonObjects.get(beanName);
        // 没有从 earlySingletonObjects 缓存中获取到
        if (singletonObject == null &amp;&amp; allowEarlyReference) &#123;
            synchronized (this.singletonObjects) &#123;
                // Consistent creation of early reference within full singleton lock
                // 再次获取并检查
                singletonObject = this.singletonObjects.get(beanName);
                if (singletonObject == null) &#123;
                    singletonObject = this.earlySingletonObjects.get(beanName);
                    if (singletonObject == null) &#123;
                        // private final Map&lt;String, ObjectFactory&lt;?&gt;&gt; singletonFactories = new HashMap&lt;&gt;(16);
                        // 从 singletonFactories 缓存中获取
                        ObjectFactory&lt;?&gt; singletonFactory = this.singletonFactories.get(beanName);
                        if (singletonFactory != null) &#123;
                            singletonObject = singletonFactory.getObject();
                            // 添加到 earlySingletonObjects 缓存中
                            this.earlySingletonObjects.put(beanName, singletonObject);
                            // 从 singletonFactories 缓存中删除
                            this.singletonFactories.remove(beanName);
                        &#125;
                    &#125;
                &#125;
            &#125;
        &#125;
    &#125;
    return singletonObject;
&#125;</code></pre>
<p>这里可以看出，获取一个 Bean ：</p>
<ol>
<li>先从 <code>singletonObjects</code> 中获取 Bean；</li>
<li>获取不到，从 <code>earlySingletonObjects</code> 中获取 Bean；</li>
<li>获取不到，从 <code>singletonFactories</code> 中获取 Bean。</li>
</ol>
<p>当然这一块涉及到循环引用，篇幅有限，后面会专门介绍循环引用。</p>
<ul>
<li>没有从缓存中获取到 Bean，创建对应的 Bean</li>
</ul>
<pre><code class="java">// Create bean instance.
if (mbd.isSingleton()) &#123;
    // 单例 bean
    sharedInstance = getSingleton(beanName, () -&gt; &#123;
        try &#123;
            return createBean(beanName, mbd, args);
        &#125;
        catch (BeansException ex) &#123;
            // Explicitly remove instance from singleton cache: It might have been put there
            // eagerly by the creation process, to allow for circular reference resolution.
            // Also remove any beans that received a temporary reference to the bean.
            destroySingleton(beanName);
            throw ex;
        &#125;
    &#125;);
    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
&#125; else if (mbd.isPrototype()) &#123;
    // 创建原型Bean

&#125; else &#123;
    // 委托给实现类处理
    String scopeName = mbd.getScope();
&#125;</code></pre>
<ul>
<li>检查所需的类型是否与实际bean实例的类型匹配</li>
</ul>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>这里主要介绍了 Bean 的创建过程，主要是对整个过程有个大概的了解和熟悉，针对过程画图如下：</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/II1QBD-L3tiN3.png"></p>
<p>其中 Bean 的实例化主要关注单例 Bean 的实例化，后面准备对其进行详细研究后，再进行说明。</p>
<h4 id="相关推荐"><a href="#相关推荐" class="headerlink" title="相关推荐"></a>相关推荐</h4><ul>
<li><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/bKmqVFuLLLCquWf3tzH30g">Spring 源码学习 14：initApplicationEventMulticaster</a></li>
<li><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/99IdvVkTULwTcxrxhF84Ew">Spring 源码学习 13：initMessageSource</a></li>
<li><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/QrogJIm9OaUmeRk9tGiNeg">Spring 源码学习 12：registerBeanPostProcessors</a></li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">liuzhihang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://liuzhihang.com/2021/01/12/source-spring-15.html">https://liuzhihang.com/2021/01/12/source-spring-15.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://liuzhihang.com" target="_blank">程序员小航</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring/">Spring</a><a class="post-meta__tags" href="/tags/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/II1QBD-L3tiN3.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/01/17/source-spring-16.html"><img class="prev-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/fybVmp-2dcCmU.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Spring 源码学习 16：单例 Bean 创建</div></div></a></div><div class="next-post pull-right"><a href="/2021/01/05/source-spring-14.html"><img class="next-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/KgCNdp-V1Ov1L.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Spring 源码学习 14：initApplicationEventMulticaster 、onRefresh 和 registerListeners</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2020/12/28/source-spring-11.html" title="Spring 源码学习 11：invokeBeanFactoryPostProcessors"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/hoPCO0-yAfXNu.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">Spring 源码学习 11：invokeBeanFactoryPostProcessors</div></div></a></div><div><a href="/2020/12/27/source-spring-10.html" title="Spring 源码学习 10：prepareBeanFactory 和 postProcessBeanFactory"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/nDmWFO-dHVLOp.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-27</div><div class="title">Spring 源码学习 10：prepareBeanFactory 和 postProcessBeanFactory</div></div></a></div><div><a href="/2021/01/01/source-spring-12.html" title="Spring 源码学习 12：registerBeanPostProcessors"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/dHDiOq-CxKXF8.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-01</div><div class="title">Spring 源码学习 12：registerBeanPostProcessors</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">liuzhihang</div><div class="author-info__description">学，然后知不足；教，然后知困。</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liuzhihang"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liuzhihang" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&amp;email=Vjo-Iyw_Pz43ODElFicneDU5Ow" target="_blank" title="Email"><i class="fas fa-envelope-open"></i></a><a class="social-icon" href="https://weibo.com/onlyhang" target="_blank" title="Weibo"><i class="fab fa-weibo"></i></a><a class="social-icon" href="https://twitter.com/liuzhihangs" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="fas fa-rss"></i></a><a class="social-icon" href="https://www.infoq.cn/u/liuzhihang/publish" target="_blank" title="InfoQ"><i class="iconfont iconweibiaoti-1"></i></a><a class="social-icon" href="https://juejin.im/user/1987506650493117" target="_blank" title="掘金"><i class="iconfont iconjuejin-1"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_36535538" target="_blank" title="CSDN"><i class="iconfont iconcsdn"></i></a><a class="social-icon" href="https://www.zhihu.com/people/liuzhihang" target="_blank" title="知乎"><i class="iconfont iconzhihu1"></i></a><a class="social-icon" href="https://leetcode-cn.com/u/liuzhihang" target="_blank" title="LeetCode"><i class="iconfont iconleetcode"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">🧑‍💻感谢访问本站，若喜欢请收藏 ^_^ <br> <br> <img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/wechat.jpg"> <br> 个人公众号:『 程序员小航 』</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-text">前言</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF-FactoryBean-%EF%BC%9F"><span class="toc-text">什么是 FactoryBean ？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8"><span class="toc-text">使用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-PaidComponent"><span class="toc-text">1. PaidComponent</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-PaidComponentFactoryBean"><span class="toc-text">2. PaidComponentFactoryBean</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-Test"><span class="toc-text">3 Test</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#finishBeanFactoryInitialization-%E6%BA%90%E7%A0%81"><span class="toc-text">finishBeanFactoryInitialization 源码</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#preInstantiateSingletons"><span class="toc-text">preInstantiateSingletons</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#getBean"><span class="toc-text">getBean</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#doGetBean"><span class="toc-text">doGetBean</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-text">总结</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%9B%B8%E5%85%B3%E6%8E%A8%E8%8D%90"><span class="toc-text">相关推荐</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/uztio4-T5n5Wm.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="使用 SpringBoot 转换器将前端参数转换为枚举"/></a><div class="content"><a class="title" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举">使用 SpringBoot 转换器将前端参数转换为枚举</a><time datetime="2021-09-03T23:00:00.000Z" title="发表于 2021-09-04 07:00:00">2021-09-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ze1d2z-wXDWp0.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="MyBatis-Plus 中 Mapper 重载踩坑指南"/></a><div class="content"><a class="title" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南">MyBatis-Plus 中 Mapper 重载踩坑指南</a><time datetime="2021-08-21T23:00:00.000Z" title="发表于 2021-08-22 07:00:00">2021-08-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/MODJ8j-9ObHeB.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="并发场景加锁优化小技巧"/></a><div class="content"><a class="title" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧">并发场景加锁优化小技巧</a><time datetime="2021-07-24T23:00:00.000Z" title="发表于 2021-07-25 07:00:00">2021-07-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"/></a><div class="content"><a class="title" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁">ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁</a><time datetime="2021-07-16T13:30:30.000Z" title="发表于 2021-07-16 21:30:30">2021-07-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"/></a><div class="content"><a class="title" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁">ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁</a><time datetime="2021-07-15T13:30:30.000Z" title="发表于 2021-07-15 21:30:30">2021-07-15</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2017 - 2021 By liuzhihang</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><img class="icp-icon" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="/resources/image/icp.png"><span>备案号：京ICP备20000888号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>function addGitalkSource () {
  const ele = document.createElement('link')
  ele.rel = 'stylesheet'
  ele.href= 'https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css'
  document.getElementsByTagName('head')[0].appendChild(ele)
}

function loadGitalk () {
  function initGitalk () {
    var gitalk = new Gitalk(Object.assign({
      clientID: 'e48f300349e2ac2d03bd',
      clientSecret: '001c669e6269dfd9d7d9fef029cc71fd00ea69e3',
      repo: 'comments',
      owner: 'liuzhihang',
      admin: ['liuzhihang'],
      id: 'de2d1352e171a2ae99bd92df7fb22861',
      language: 'en',
      perPage: 10,
      distractionFreeMode: false,
      pagerDirection: 'last',
      createIssueManually: false,
      updateCountCallback: commentCount
    },null))

    gitalk.render('gitalk-container')
  }

  if (typeof Gitalk === 'function') initGitalk()
  else {
    addGitalkSource()
    getScript('https://cdn.jsdelivr.net/npm/gitalk@latest/dist/gitalk.min.js').then(initGitalk)
  }
}

function commentCount(n){
  let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
  if (isCommentCount) {
    isCommentCount.innerHTML= n
  }
}

if ('Gitalk' === 'Gitalk' || !false) {
  if (false) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
  else loadGitalk()
} else {
  function loadOtherComment () {
    loadGitalk()
  }
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>